import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;

public class InitVotes {
    // JDBC 连接参数，请根据实际情况修改
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/votes"
            + "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    private static final String JDBC_USER = "root";
    private static final String JDBC_PASS = "your_password_for_mysql";

    // 要扫描的目录
    private static final String IMAGE_DIR = "D:\\Private\\PracticalTraining\\AccountManage\\Characters";

    public static void main(String[] args) {
        // 加载 JDBC 驱动（可选，现代 JDBC 驱动会自动注册）
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC Driver not found.");
            e.printStackTrace();
            return;
        }

        // 扫描并上传
        try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS)) {
            conn.setAutoCommit(false);

            String sql = "INSERT INTO images (image_data, image_name, vote_count) VALUES (?, ?, ?)";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                File dir = new File(IMAGE_DIR);
                File[] files = dir.listFiles((d, name) -> {
                    String lower = name.toLowerCase();
                    return lower.endsWith(".jpg")
                            || lower.endsWith(".jpeg")
                            || lower.endsWith(".png")
                            || lower.endsWith(".gif");
                });

                if (files == null) {
                    System.err.println("目录不存在或无法读取: " + IMAGE_DIR);
                    return;
                }

                for (File file : files) {
                    String filename = file.getName();
                    String nameWithoutExt = filename.replaceFirst("\\.[^.]+$", "");

                    byte[] data;
                    try {
                        data = Files.readAllBytes(Path.of(file.getAbsolutePath()));
                    } catch (IOException ioe) {
                        System.err.println("读取文件失败: " + file.getAbsolutePath());
                        ioe.printStackTrace();
                        continue;
                    }

                    ps.setBytes(1, data);
                    ps.setString(2, nameWithoutExt);
                    ps.setInt(3, 0);
                    ps.addBatch();
                }

                int[] results = ps.executeBatch();
                conn.commit();
                System.out.println("共插入图片 " + results.length + " 条记录。");
            } catch (SQLException e) {
                conn.rollback();
                System.err.println("批量插入失败，已回滚。");
                e.printStackTrace();
            }
        } catch (SQLException e) {
            System.err.println("无法连接到数据库");
            e.printStackTrace();
        }
    }
}
